package com.jn.algorithm.day020.question59;

import java.util.Arrays;

/**
 * @author 江南大学1033190417
 * @date 2022/5/11 14:41
 */
public class Solution {
    public int[][] generateMatrix(int n) {
        if (n == 1) {
            return new int[][]{{1}};
        }
        int[][] res = new int[n][n];
        int layer = 0;//层
        int num = 1;//当前数
        while (layer < n - 1) {
            //填写上
            for (int i = layer; i < n - layer; i++) {
                res[layer][i] = num++;
            }
            //填写右
            for (int i = layer + 1; i < n - layer; i++) {
                res[i][n - layer - 1] = num++;
            }
            //填写下
            for (int i = n - layer - 2; i >= layer; i--) {
                res[n - layer - 1][i] = num++;
            }
            //填写左
            for (int i = n - layer - 2; i > layer; i--) {
                res[i][layer] = num++;
            }

            layer++;
        }
        return res;
    }

    public void print(int[][] arr) {
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] ints = solution.generateMatrix(4);
        solution.print(ints);
    }
}
